package pers.wang.toolset.ali.rocketmq.spring.boot.autoconfigure;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;

public class MessageListener implements com.aliyun.openservices.ons.api.MessageListener,ApplicationContextAware {
	private static final Logger LOG = LoggerFactory.getLogger(MessageListener.class);
	private MessageCallback callback;
	@Override
	public Action consume(Message message, ConsumeContext context) {
		LOG.info("消费消息：{}-{}",message.getKey(),new String(message.getBody()));
		Action action = Action.ReconsumeLater;
		try {
			boolean consumeResult = callback.consume(message);
			action = consumeResult ? Action.CommitMessage : action;
		} catch (Exception e) {
			LOG.error("消费消息失败，消息：{},错误信息：{}",new String(message.getBody()),e);
		}
		return action;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		Map<String, MessageCallback> callbackMap = applicationContext.getBeansOfType(MessageCallback.class);
		if(callbackMap.size() == 0) {
			LOG.error("未发现消费者消息callback");
			throw new Error("未发现消费者消息callback") ;
		}
		if(callbackMap.size() > 1) {
			LOG.error("发现多个消费者消息callback");
			throw new Error("发现多个消费者消息callback:" + callbackMap) ;
		}
		callbackMap.forEach((name,bean) ->{
			this.callback = bean;
			LOG.info("消费者消息callback:beanName:{},beanClass:{}",name,bean.getClass());
		});
	}

}
